package com.jacklin.shopping.mall.service.Impl;

import com.lbz.common.Constant;
import com.lbz.common.ServerResponse;
import com.lbz.common.TokenCache;
import com.lbz.dao.UserMapper;
import com.lbz.entity.User;
import com.lbz.service.UserService;
import com.lbz.utils.MD5Util;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @Author 林必昭
 * @Date 2019/6/16 16:36
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    /**
     * 用户注册
     * @param user
     * @return
     */
    @Override
    public ServerResponse<String> register(User user) {
        ServerResponse<String> validResponse = checkValid(user.getUsername(), Constant.USERNAME);
        if (!validResponse.isSuccess()){
            return validResponse;
        }
        validResponse = this.checkValid(user.getUsername(),Constant.EMAIL);
        if (!validResponse.isSuccess()){
            return validResponse;
        }
//        user.setRole(Constant.Role.ROLE_CUSTOMER);
        //MD5加密密码
        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        int resultCount = userMapper.insert(user);
        if (resultCount == 0){
            return ServerResponse.createByErrorMessage("注册失败");
        }
        return ServerResponse.createBySuccessMessage("注册成功");

    }

    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @Override
    public ServerResponse<User> login(String username, String password) {
        int resultCount = userMapper.checkUsername(username);
        if (resultCount==0){
            return ServerResponse.createByErrorMessage("用户名不存在");
        }
        String MD5Password = MD5Util.MD5EncodeUtf8(password);
        User user = userMapper.checkLogin(username, MD5Password);
        if (user == null){
            return ServerResponse.createBySuccessMessage("密码错误");
        }
        user.setPassword(StringUtils.EMPTY);    //置空密码
        return ServerResponse.createBySuccess("登录成功",user);
    }

    /**
     * 检查用户名是否有效
     *
     * 当response.isSuccess()表明用户不存在
     * @param str
     * @param type
     * @return
     */
    @Override
    public ServerResponse<String> checkValid(String str, String type){
        if(org.apache.commons.lang3.StringUtils.isNotBlank(type)){
            //开始校验
            if(Constant.USERNAME.equals(type)){
                int resultCount = userMapper.checkUsername(str);
                if(resultCount > 0 ){
                    return ServerResponse.createByErrorMessage("用户名已存在");
                }
            }
            if(Constant.EMAIL.equals(type)){
                int resultCount = userMapper.checkEmail(str);
                if(resultCount > 0 ){
                    return ServerResponse.createByErrorMessage("email已存在");
                }
            }
        }else{
            return ServerResponse.createByErrorMessage("参数错误");
        }
        return ServerResponse.createBySuccessMessage("校验成功");
    }

    /**
     * 检测是否是管理员身份
     * @param user
     * @return
     */
    @Override
    public ServerResponse checkRoleAdmin(User user) {
        if (user!=null && user.getRole().intValue()==(Constant.Role.ROLE_ADMIN)){
            return ServerResponse.createBySuccess();
        }
        return ServerResponse.createByError();
    }

    @Override
    public ServerResponse selectQuestion(String username) {
        ServerResponse validResponse = this.checkValid(username, Constant.USERNAME);
        if (validResponse.isSuccess()){
            //用户不存在
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        String question = userMapper.selectQuestionByUsername(username);
        if (StringUtils.isNotBlank(question)){
            //返回找回密码问题
            return ServerResponse.createBySuccess(question);
        }
        return ServerResponse.createByErrorMessage("找回密码的问题时空的");
    }

    /**
     * 判断找回密码的答案，如果答案与创建用户时设置的一致，证明是当前用户，那么就会返回一个forgetToken，为重置密码提供token
     * @param username
     * @param question
     * @param answer
     * @return
     */
    @Override
    public ServerResponse<String> checkAnswer(String username, String question, String answer) {
        int rowCount = userMapper.checkAnswer(username, question, answer);
        if (rowCount>0){
            //说明问题以及问题密码与当前用户相匹配，然后生成token用来找回密码使用
            String forgetToken = UUID.randomUUID().toString();  //利用UUID来生成token
            //创建一个类TokenCache用来存放token信息
            TokenCache.setKey(TokenCache.TOKEN_PREFIX+username,forgetToken);    //key:token_username value:forgetToken
            return ServerResponse.createBySuccess(forgetToken); //返回一个token，传递给下一个接口用来做密码修改
        }
        return ServerResponse.createByErrorMessage("问题的答案错误");
    }

    @Override
    public ServerResponse<String> resetPassword(String passwordOld, String passwordNew, User user) {
        /*
            为了防止横向越权，需要校验一下这个用户的额旧密码，一定要指定是当前用户，一次我们会查询一个count(1)出来，
            如果不指定id，那么结果就为true，count>0
         */
        int resultCount = userMapper.checkPassword(MD5Util.MD5EncodeUtf8(passwordOld), user.getId());
        if (resultCount == 0){
            return ServerResponse.createByErrorMessage("旧密码错误");
        }
        user.setPassword(MD5Util.MD5EncodeUtf8(passwordNew));
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if (updateCount>0){
            return ServerResponse.createBySuccessMessage("密码更新成功");
        }
        return ServerResponse.createByErrorMessage("密码更新失败");
    }

    /**
     * 忘记密码下的重置密码逻辑->
     * 1.需要获取终止密码的token
     * 2.检查用户是否存在
     * 3.判断传入的forgetToken与存储在cache里的token是否一致
     * 4.如果不一致需要再重新获取token
     * 5.重置密码成功
     * @param username
     * @param passwordNew
     * @param forgetToken
     * @return
     */
    @Override
    public ServerResponse<String> forgetResetPassword(String username, String passwordNew, String forgetToken) {
        if (StringUtils.isBlank(forgetToken)){
            return ServerResponse.createByErrorMessage("参数错误，token需要传参");
        }
        ServerResponse<String> validResponse = this.checkValid(username, Constant.USERNAME);
        if (validResponse.isSuccess()){
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        //通过getValue获取cache里面的token，与传入的进行比较
        String token = TokenCache.getValue(TokenCache.TOKEN_PREFIX+username);
        if (StringUtils.isBlank(token)){
            return ServerResponse.createByErrorMessage("token无效或过期");
        }
        if (StringUtils.equals(forgetToken,token)){
            String md5Password = MD5Util.MD5EncodeUtf8(passwordNew);
            int rowCount = userMapper.updatePasswordByUsername(username, md5Password);
            if (rowCount>0){
                return ServerResponse.createBySuccessMessage("修改密码成功");
            }
        }else {
            return ServerResponse.createByErrorMessage("token错误，请重新获取重置密码token");
        }
        return ServerResponse.createByErrorMessage("修改密码失败");
    }

    /**
     * 更新用户信息逻辑->
     * 1.用户名是不能更新的
     * 2.判断更改的email是否存在
     *
     * @param user
     * @return
     */
    @Override
    public ServerResponse<User> updateInformation(User user) {
        int rowCount = userMapper.checkEmailByUserId(user.getEmail(), user.getId());
        if (rowCount>0){
            return ServerResponse.createByErrorMessage("email已存在，请更换email再尝试更新");
        }
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setEmail(user.getEmail());
        updateUser.setPhone(user.getPhone());
        updateUser.setQuestion(user.getQuestion());
        updateUser.setAnswer(user.getAnswer());

        int updateCount = userMapper.updateByPrimaryKeySelective(updateUser);
        if (updateCount>0){
            return ServerResponse.createBySuccess("更新个人信息成功",updateUser);
        }
        return ServerResponse.createByErrorMessage("更新个人信息失败");
    }

    @Override
    public ServerResponse<User> getInformation(Integer userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        if (user==null){
            return ServerResponse.createByErrorMessage("找不到当前用户信息");
        }
        user.setPassword(StringUtils.EMPTY);    //密码置空
        return ServerResponse.createBySuccess(user);
    }
}
